import {UIElement, UIPanel} from '../../js/threejs/libs/ui.js'

export default class ContentLeftDeviceList {
  constructor(displayer) {
    let scope = this

    const treeSetting = {
      view: {
        addHoverDom: null,
        removeHoverDom: null,
        addDiyDom: this.addDiyDom
      }
    };
    let container = new UIPanel()
    container.setId('panel-device')
    container.setClass('panel-device')
    this.container = container

    container.dom.innerHTML = `<div class="title"><img src="images/icon02.png"  alt=""/> 设备列表 </div>`

    // let deviceList = new UIOutliner(displayer)
    // deviceList.setClass('device-list')
    // deviceList.onClick(function (e) {
    //   console.log(e.target.nodeName)
    //   if (e.target.nodeName === 'A') {
    //     // 注释此行，点击设备列表更新设备信息（如果设备信息页显示）
    //     displayer.selectByUuid(deviceList.getValue())
    //     displayer.focusByUuid(deviceList.getValue())
    //   }
    // })
    // container.add(deviceList)


    let treetableUI = new UIElement(document.createElement('div'))
    treetableUI.dom.innerHTML =
        `<div class="zTreeDemoBackground left">
        \t<ul id="device-tree" class="device-tree ztree"></ul>
        </div>`
    container.add(treetableUI)

    displayer.signals.deployConfigLoaded.add(() => {
      const start = performance.now();
      displayer.request.getAction('/display/getDeviceData', {sceneId: displayer.deployConfig.id}).then((res) => {
        if (res.success) {
          const zNodes = scope.treeData(res.result)
          $(document).ready(function () {
            $.fn.zTree.init($("#device-tree"), treeSetting, zNodes);
            console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', 'getDeviceData. ' + (performance.now() - start).toFixed(2) + 'ms');
          })
        } else {
          console.error(res.message)
        }
      })
    })

    window.setTimeout(() => {
      displayer.signals.dataReceived.add(receiveData => {
        scope.updateDeviceData(receiveData)
      })
    }, 500)

  }

  treeData(data) {
    let cloneData = JSON.parse(JSON.stringify(data))
    return cloneData.filter(father => {
      let branchArr = cloneData.filter(child => father['id'] === child['parentBy']);
      branchArr.length > 0 ? father['children'] = branchArr : '';
      return father['parentBy'] === undefined;
    })
  }

  // addDiyDom(treeId, treeNode) {
  //   let scope = this
  //   console.log(treeId, treeNode)
  //   const aObj = $("#" + treeNode.tId + "_a");
  //   const editStr = `<button type="button" class="diyBtn1" id="diyBtn_${treeNode.id}">${treeNode.name}</button>`
  //   aObj.append(editStr);
  // }

  addDiyDom(treeId, treeNode) {
    let scope = this
    // console.log(treeId, treeNode)
    const aObj = document.getElementById(treeNode.tId + "_a");
    const datas = treeNode['deviceDatas']
    if (datas !== undefined && datas.length > 0) {
      let select = document.createElement('select')
      select.id = treeNode.id
      datas
          .filter((data) => data.metadata !== undefined && data['rwAuthor'] === 'r')
          .map((data) => {
            let unit = data.metadata['unitSymbol'] || ''
            let option = document.createElement('option')
            let value = data['latestData']['dataObj'][data.code] === null ? '' : data['latestData']['dataObj'][data.code]
            option.innerHTML = `${data.name}：${value} ${unit}`
            option.value = data.code
            option.id = treeNode.id + '-' + data.code
            option.style.margin = '8px 0px'
            option.className = ''
            select.appendChild(option)
          })
      if (select.childElementCount <= 0) {
        select.style.display = 'none'
      }
      aObj.appendChild(select)
    }
  }

  /**
   * 构建数据节点，下拉选择一项显示
   * @returns {*}
   * @param deviceInstances
   */
  buildDataOption(deviceInstances) {
    let scope = this
    return deviceInstances.map((instance) => {
      let option = document.createElement('div')
      option.style.display = 'flex'
      option.draggable = true
      option.value = instance.id
      let deviceName = document.createElement('div')
      deviceName.className = 'device-name'
      deviceName.innerHTML = `<a href="javascript:;">${instance.name}</a>`
      // 追加设备名称
      option.appendChild(deviceName)

      // 追加事件标记：心跳、数据、报警
      let eventFlag = document.createElement('div')
      eventFlag.className = 'event-flag'
      // 心跳
      let heart = document.createElement('div')
      heart.className = 'heart'
      heart.id = instance.id + '-heart'
      eventFlag.appendChild(heart)
      // 数据
      let data = document.createElement('div')
      data.id = instance.id + '-data'
      data.className = 'data'
      eventFlag.appendChild(data)
      // 报警
      let alarm = document.createElement('div')
      alarm.id = instance.id + '-alarm'
      alarm.className = 'alarm'
      eventFlag.appendChild(alarm)

      option.appendChild(eventFlag)

      let datas = instance['instanceDatas']
      if (datas !== undefined && datas.length > 0) {
        option.appendChild(scope.buildDataSelect(instance.id, datas))
      }
      return option
    })
  }

  buildDataSelect(deviceInstanceId, modelDatas) {
    let select = document.createElement('select')
    select.id = deviceInstanceId
    modelDatas
      .filter((data) => data.metadata !== undefined && data['rwAuthor'] === 'r')
      .map((data) => {
        let unit = data.metadata['unit'] || ''
        let option = document.createElement('option')
        let value = data['latestData']['value'] === null ? data.metadata.defaultValue||'' : data.latestData.value
        option.innerHTML = `${data.name}：${value} ${unit.substring(unit.indexOf('[') + 1, unit.indexOf(']'))}`
        option.value = data.code
        option.id = deviceInstanceId + '-' + data.code
        option.style.margin = '8px 0px'
        option.className = ''
        select.appendChild(option)
      })
    if (select.childElementCount <= 0) {
      select.style.display = 'none'
    }
    return select
  }

  updateDeviceData(receiveData) {
    receiveData.map(data => {
      // instance.id + '-data'
      let dataIcon = document.getElementById((data.instanceId + '-data'))
      if(dataIcon) {
        dataIcon.style.display = 'block'
        window.setTimeout(() => {
          dataIcon.style.display = 'none'
        }, 300)
      }
      let option = document.getElementById((data.instanceId + '-' + data.code))
      let unit = data.metadata['unit'] || ''
      option.innerHTML = `${data.name}：${data['latestData']['value'] || ''} ${unit.substring(unit.indexOf('[') + 1, unit.indexOf(']'))}`
    })
  }
}